/**
 * API统一导出文件
 * 提供便捷的API调用方法
 */

import httpRequest from './request';
import { API_CONFIG } from './config';

/**
 * 用户相关API
 */
export const userAPI = {
  /**
   * 发送验证码
   * @param {string} phone - 手机号
   * @returns {Promise} 返回验证码发送结果
   */
  sendCode: phone => {
    return httpRequest.get('/travel/app/sms/code', {
      phonenumber: phone,
    });
  },

  /**
   * 验证码登录
   * @param {string} phone - 手机号
   * @param {string} code - 验证码
   * @returns {Promise} 返回登录结果，包含token和用户信息
   */
  loginWithCode: (phone, code) => {
    return httpRequest.post('/travel/app/auth/smsLogin', {
      grantType: 'smsXcx', // 固定值：短信小程序登录
      phonenumber: phone, // 手机号（动态）
      smsCode: code, // 验证码（动态）
      tenantId: '000000', // 固定值：租户ID
    });
  },

  /**
   * 退出登录
   */
  logout: () => {
    return httpRequest.post(API_CONFIG.ENDPOINTS.LOGOUT);
  },

  /**
   * 获取用户信息
   * @returns {Promise} 返回用户详细信息
   */
  getProfile: () => {
    return httpRequest.get('/travel/app/user/userInfo');
  },

  /**
   * 更新用户信息
   * @param {Object} userData - 用户数据
   * @param {string} userData.nickname - 用户昵称 (2-50字符)
   * @param {number} userData.sex - 性别 (0=未知/1=男/2=女)
   * @param {string} userData.tel - 手机号码 (11位)
   * @param {string} userData.address - 详细地址 (最长200字符)
   * @param {string} userData.remark - 个人简介 (最长500字符)
   * @param {string} userData.avatar - 头像URL
   */
  updateProfile: userData => {
    return httpRequest.post('/travel/app/user/update', userData);
  },

  /**
   * 上传文件（头像等）
   * @param {Object} file - 文件对象
   * @param {string} type - 文件类型 (如 'avatar')
   */
  uploadFile: (file, type = 'avatar') => {
    return httpRequest.upload('/travel/app/upload/upload', file, { type });
  },
};

/**
 * 景点相关API
 */
export const attractionAPI = {
  // 获取景点列表
  getAttractions: (params = {}) => {
    return httpRequest.get(API_CONFIG.ENDPOINTS.ATTRACTIONS, params);
  },

  // 获取景点详情
  getAttractionDetail: id => {
    return httpRequest.get(
      API_CONFIG.ENDPOINTS.ATTRACTION_DETAIL,
      {},
      {
        pathParams: { id },
      },
    );
  },

  // 搜索景点
  searchAttractions: (keyword, params = {}) => {
    return httpRequest.get(API_CONFIG.ENDPOINTS.ATTRACTION_SEARCH, {
      keyword,
      ...params,
    });
  },

  // 获取附近景点
  getNearbyAttractions: (latitude, longitude, radius = 10) => {
    return httpRequest.get(API_CONFIG.ENDPOINTS.ATTRACTION_NEARBY, {
      latitude,
      longitude,
      radius,
    });
  },

  // 创建景点（管理员功能）
  createAttraction: attractionData => {
    return httpRequest.post(API_CONFIG.ENDPOINTS.ATTRACTIONS, attractionData);
  },

  // 更新景点（管理员功能）
  updateAttraction: (id, attractionData) => {
    return httpRequest.put(
      API_CONFIG.ENDPOINTS.ATTRACTION_DETAIL,
      attractionData,
      {
        pathParams: { id },
      },
    );
  },

  // 删除景点（管理员功能）
  deleteAttraction: id => {
    return httpRequest.delete(API_CONFIG.ENDPOINTS.ATTRACTION_DETAIL, {
      pathParams: { id },
    });
  },
};

/**
 * 美食文化API
 */
export const foodCultureAPI = {
  // 获取美食文化列表
  getFoodCultures: (params = {}) => {
    return httpRequest.get(API_CONFIG.ENDPOINTS.FOOD_CULTURE, params);
  },

  // 获取美食文化详情
  getFoodCultureDetail: id => {
    return httpRequest.get(
      API_CONFIG.ENDPOINTS.FOOD_CULTURE_DETAIL,
      {},
      {
        pathParams: { id },
      },
    );
  },

  // 获取美食与文创分页列表
  getFoodCulturePage: (params = {}) => {
    return httpRequest.get('/travel/app/foodCulture/page', {
      city: params.city,
      pageNum: params.pageNum || '1',
      pageSize: params.pageSize || '10',
      type: params.type, // 1为美食，2为文创
    });
  },

  // 获取美食与文创详情
  getFoodCultureDetailById: id => {
    return httpRequest.get(`/travel/app/foodCulture/${id}`);
  },

  // 创建美食文化
  createFoodCulture: data => {
    return httpRequest.post(API_CONFIG.ENDPOINTS.FOOD_CULTURE, data);
  },

  // 更新美食文化
  updateFoodCulture: (id, data) => {
    return httpRequest.put(API_CONFIG.ENDPOINTS.FOOD_CULTURE_DETAIL, data, {
      pathParams: { id },
    });
  },

  // 删除美食文化
  deleteFoodCulture: id => {
    return httpRequest.delete(API_CONFIG.ENDPOINTS.FOOD_CULTURE_DETAIL, {
      pathParams: { id },
    });
  },
};

/**
 * 省份景点API
 */
export const provinceAPI = {
  // 获取省份景点
  getProvinceAttractions: (province, params = {}) => {
    return httpRequest.get(API_CONFIG.ENDPOINTS.PROVINCE_ATTRACTIONS, params, {
      pathParams: { province },
    });
  },

  // 获取跨省路线
  getCrossProvinceRoutes: (params = {}) => {
    return httpRequest.get(API_CONFIG.ENDPOINTS.CROSS_PROVINCE_ROUTES, params);
  },
};

/**
 * 文件上传API
 */
export const uploadAPI = {
  // 上传图片
  uploadImage: (file, data = {}, onProgress = null) => {
    return httpRequest.upload(
      API_CONFIG.ENDPOINTS.UPLOAD_IMAGE,
      file,
      data,
      onProgress,
    );
  },

  // 上传音频
  uploadAudio: (file, data = {}, onProgress = null) => {
    return httpRequest.upload(
      API_CONFIG.ENDPOINTS.UPLOAD_AUDIO,
      file,
      data,
      onProgress,
    );
  },

  // 上传视频
  uploadVideo: (file, data = {}, onProgress = null) => {
    return httpRequest.upload(
      API_CONFIG.ENDPOINTS.UPLOAD_VIDEO,
      file,
      data,
      onProgress,
    );
  },

  // 通用文件上传
  uploadFile: (url, file, data = {}, onProgress = null) => {
    return httpRequest.upload(url, file, data, onProgress);
  },
};

/**
 * 位置相关API
 */
export const locationAPI = {
  // 根据经纬度获取位置信息
  getLocationByLonLat: (lon, lat) => {
    return httpRequest.get('/travel/app/scenicStatistics/getLocationByLonLat', {
      lon: lon.toString(),
      lat: lat.toString(),
    });
  },
  // 根据城市代码获取辖区景点数量统计
  countByCityCode: async cityCode => {
    const response = await httpRequest.get(
      '/travel/app/scenicStatistics/count',
      {
        cityCode: cityCode != null ? String(cityCode) : undefined,
      },
    );
    return response;
  },
  // 获取首页实时天气
  getActualWeather: cityAdcode => {
    return httpRequest.get('/travel/app/scenicStatistics/getActualWeather', {
      cityAdcode: cityAdcode != null ? String(cityAdcode) : undefined,
    });
  },
  // 获取最近的景区数据（大图标+小图标）
  getCityScenicAreasWithSpots: (params = {}) => {
    return httpRequest.get(
      '/travel/app/scenicStatistics/getNearestScenicAreaWithSpots',
      {
        cityCode: params.cityCode,
        latitude: params.latitude,
        longitude: params.longitude,
      },
    );
  },
  // 获取地图上展示的景区数据（只需要城市代码）
  getMapScenicAreas: cityCode => {
    return httpRequest.get('/travel/app/scenicStatistics/count', {
      cityCode,
    });
  },
  // 获取周边景区数据
  getOtherScenicAreas: (params = {}) => {
    return httpRequest.get('/travel/app/scenicStatistics/getOtherScenicAreas', {
      cityCode: params.cityCode,
      latitude: params.latitude,
      longitude: params.longitude,
      pageNum: params.pageNum,
      pageSize: params.pageSize,
    });
  },
  // 获取省内旅游路线数据
  getProvinceTours: (params = {}) => {
    return httpRequest.get('/travel/app/scenicStatistics/getProvinceTours', {
      cityCode: params.cityCode,
      pageNum: params.pageNum,
      pageSize: params.pageSize,
    });
  },
  // 获取跨省旅游路线数据
  getCrossProvinceTours: (params = {}) => {
    return httpRequest.get(
      '/travel/app/scenicStatistics/getCrossProvinceTours',
      {
        pageNum: params.pageNum,
        pageSize: params.pageSize,
      },
    );
  },
  // 获取景区音频和文本
  getScenicAudioAndText: scenicAreaId => {
    return httpRequest.get(
      '/travel/app/scenicStatistics/getScenicAudioAndText',
      {
        scenicAreaId: scenicAreaId.toString(),
      },
    );
  },
  // 获取景点音频和文本
  getScenicSpotAudioAndText: scenicSpotId => {
    return httpRequest.get(
      '/travel/app/scenicStatistics/getScenicSpotAudioAndText',
      {
        scenicSpotId: scenicSpotId.toString(),
      },
    );
  },
  // 获取景区下的景点列表
  getScenicAreaAttractions: (scenicAreaId, pageNum = 1, pageSize = 10) => {
    return httpRequest.get('/travel/app/scenicAreas/attractions', {
      scenicAreaId: scenicAreaId.toString(),
      pageNum: pageNum.toString(),
      pageSize: pageSize.toString(),
    });
  },
  getCityStatistics: params =>
    httpRequest.get('/travel/app/scenicStatistics/statisticsByCityCode', {
      params,
    }),
  searchScenicByKeyword: keyword =>
    httpRequest.get('/travel/app/scenicStatistics/searchScenicByKeyword', {
      keyword,
    }),
  // 获取城市列表
  getCityList: () => {
    return httpRequest.get('/travel/app/city/list');
  },
  // 根据城市code获取单一城市名称
  getCityByCode: code => {
    return httpRequest.get('/travel/app/city/getByCode', {
      code,
    });
  },
};

/**
 * 其他API
 */
export const commonAPI = {
  // 获取天气信息
  getWeather: city => {
    return httpRequest.get(API_CONFIG.ENDPOINTS.WEATHER, { city });
  },

  // 检查版本更新
  checkVersion: () => {
    return httpRequest.get(API_CONFIG.ENDPOINTS.VERSION_CHECK);
  },

  // 获取关于我们列表
  getAboutUsList: () => {
    return httpRequest.get('/travel/app/aboutUs/list');
  },

  // 提交反馈
  submitFeedback: feedbackData => {
    return httpRequest.post('/travel/app/feedbackSubmit/submit', feedbackData);
  },

  // 上传文件（通用）
  uploadFile: (file, data = {}) => {
    return httpRequest.upload('/travel/app/upload/upload', file, data);
  },
};

/**
 * 直接导出HTTP请求实例，用于自定义请求
 */
export { default as http } from './request';
export { API_CONFIG } from './config';

/**
 * 便捷方法 - 直接使用HTTP方法
 */
export const api = {
  get: httpRequest.get.bind(httpRequest),
  post: httpRequest.post.bind(httpRequest),
  put: httpRequest.put.bind(httpRequest),
  delete: httpRequest.delete.bind(httpRequest),
  patch: httpRequest.patch.bind(httpRequest),
  upload: httpRequest.upload.bind(httpRequest),
};

/**
 * 默认导出所有API
 */
export default {
  user: userAPI,
  attraction: attractionAPI,
  foodCulture: foodCultureAPI,
  province: provinceAPI,
  location: locationAPI,
  upload: uploadAPI,
  common: commonAPI,
  http: httpRequest,
  api,
};
